package com.feicheng.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.feicheng.common.constant.Constant;
import com.feicheng.common.mqtt.*;
import com.feicheng.common.task.Cache;
import com.feicheng.persistence.entity.Adz;
import com.feicheng.persistence.entity.Amdjl;
import com.feicheng.persistence.entity.Amenjin;
import com.feicheng.persistence.entity.Astore;
import com.feicheng.persistence.mapper.AkechengskjlMapper;
import com.feicheng.persistence.model.SkjlModel;
import com.feicheng.persistence.service.*;
import com.feicheng.service.a.FDzService;
import com.feicheng.service.a.FJlService;
import com.feicheng.service.a.FMjService;
import com.feicheng.service.a.FXyService;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Iterator;
import java.util.List;


@Slf4j
@Service
public class FMjConnectionService {

    @Autowired
    Cache cache;

    @Autowired
    FMjService mjService;

    @Autowired
    IAdzService dzService;

    @Autowired
    IAmdjlService mdjlService;

    @Autowired
    IAkechengskjlService skjlService;

    @Autowired
    MqttOutboundChannel mqttOutboundChannel;

    @Autowired
    IAmenjinService menjinService;

    public void cmdDeleteAllPerson(String sn) {
        String topic = "mqtt/face/"+sn;
        MqttCmd cmd = MsgFactory.deleteAllPerson(sn);
        mqttOutboundChannel.sendMessage(topic, cmd.toJSONString());
    }

    public void cmdAddPersons(String sn, JSONArray info) {
        String topic = "mqtt/face/"+sn;
        MqttCmd cmd = MsgFactory.addPersons(sn, info);
        mqttOutboundChannel.sendMessage(topic, cmd.toJSONString());
    }

    public void cmdUnlock(String sn) {
        String topic = "mqtt/face/"+sn;
        MqttCmd cmd = MsgFactory.unLock(sn);
        cmd.getInfoObject().put("openDoor", 1);
        mqttOutboundChannel.sendMessage(topic, cmd.toJSONString());
    }

    private JSONObject createDzFace(String sn, String dzid, String dname, String tx) {
        return new MqttCmd.Person()
                .customId(dzid)
                .name(dname)
                .picURI(tx)
                .tempCardType(0).build();
    }

    private JSONObject createMdjlFace(String sn, String mdjlid, String mdjlname, String tx) {
        return new MqttCmd.Person()
                .customId(mdjlid)
                .name(mdjlname)
                .picURI(tx)
                .tempCardType(0).build();
    }

    private JSONObject createJlFace(String sn, String jlid, String jlname, String jltx, String cardValidBegin, String cardValidEnd) {
        return new MqttCmd.Person()
                .customId(jlid)
                .name(jlname)
                .picURI(jltx)
                .tempCardType(1)
                .cardValidBegin(cardValidBegin)
                .cardValidEnd(cardValidEnd)
                .build();
    }

    private JSONObject createXyFace(String sn, String xyid, String xyname, String xytx, String cardValidBegin, String cardValidEnd) {
        return new MqttCmd.Person()
                .customId(xyid)
                .name(xyname)
                .picURI(xytx)
                .tempCardType(1)
                .cardValidBegin(cardValidBegin)
                .cardValidEnd(cardValidEnd)
                .build();
    }


    /**
     * 删除所有设备所有人脸，会导致设备重启上线
     */
    private void clearAllMenjin() {
        cache.initMenjin();
        List<JSONObject> mjs = mjService.allMjByStoreAndRoom(new JSONObject());
        for (JSONObject mj : mjs) {
            // 删除设备所有人脸，会导致设备重启上线
            this.cmdDeleteAllPerson(mj.getString("sn"));
            cache.putMenjin(mj);
        }
    }


    public void runDzDailyTask() {

        MqttCmd.IDS.clear();

        // 初始化所有门禁人脸名单
        this.clearAllMenjin();

    }

    /**
     * 门禁上线时调用
     * 找到门禁对用日期的所有人脸并添加到设备中
     * @param sn 设备序列号
     */
    public void addFaceToMenjin(String sn) {

        JSONArray faces = new JSONArray();

        // 从缓存中取得门禁
        JSONObject mj = cache.getMenjin(sn);

        //添加店长人脸
        faces.add(this.createDzFace(sn, mj.getString("dzid"), mj.getString("dname"), mj.getString("tx")));

        String storeid = mj.getString("storeid");
        QueryWrapper<Amdjl> mdjlqw = new QueryWrapper<>();
        mdjlqw.eq("storeid", storeid);
        List<Amdjl> mdjls = mdjlService.list(mdjlqw);
        if (null != mdjls && mdjls.size() > 0) {
            mdjls.forEach(mdjl -> {
                faces.add(this.createMdjlFace(sn, mdjl.getMdjlid(), mdjl.getMdjlname(), mdjl.getTx()));
            });
        }

        // 查询上课记录，找到上课的教练和学员
        AkechengskjlMapper skjlMapper = (AkechengskjlMapper) skjlService.getBaseMapper();
        QueryWrapper<SkjlModel> skqw = new QueryWrapper<>();
        skqw.eq("akechengitem.storeid", mj.getString("storeid"));

        /* 该门禁为房间门禁 */
        if (StringUtils.hasLength(mj.getString("roomid"))) {
            skqw.eq("akechengitem.roomid", mj.getString("roomid"));
        }

        skqw.eq("akechengskjl.dt", LocalDate.now());
        skqw.eq("akechengskjl.stu", "UD");

        List<SkjlModel> skjlList = skjlMapper.getSkjlWithKcitem(skqw);
        for (SkjlModel skjl : skjlList) {
            String dt = skjl.getDt().format(Constant.yyyyMMdd);
            String st = skjl.getSt().format(Constant.HHmm);
            String et = skjl.getEt().format(Constant.HHmm);
            String sdt = dt + " " + st + ":00";
            LocalDateTime sldt = LocalDateTime.parse(sdt, Constant.yyyyMMddHHmmss);
            sldt = sldt.minusMinutes(5L);
            sdt = sldt.format(Constant.yyyyMMddHHmmss);
            String edt = dt + " " + et + ":59";
            LocalDateTime eldt = LocalDateTime.parse(edt, Constant.yyyyMMddHHmmss);
            eldt = eldt.plusMinutes(5L);
            edt = eldt.format(Constant.yyyyMMddHHmmss);

            String jlid = skjl.getAkecheng().getJlid();
            String jlname = skjl.getAjiaolian().getJlname();
            String jltx = skjl.getAjiaolian().getTx();
            faces.add(this.createJlFace(sn, jlid, jlname, jltx, sdt, edt));

            // 将上课的学员添加到对应房间门禁待添加人脸名单中
            String clientid = skjl.getClientid();
            String clientName = skjl.getClient().getNc();
            String xytx = skjl.getClient().getTx();
            faces.add(this.createXyFace(sn, clientid, clientName, xytx, sdt, edt));
        }

        this.cmdAddPersons(sn, faces);

    }



}
